package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.controller.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("AuthorityRestController")
public class AuthorityRestController extends CmiEmaController {

	/**
	 * Create a new Authority entity
	 * 
	 */
	@RequestMapping(value = "/newAuthority", method = RequestMethod.POST)
	@ResponseBody
	public Object newAuthority(@RequestBody Authority authority) {
		authorityService.saveAuthority(authority);
		return JSONObject.parse(cmiPsonService.toJsonString(authorityDAO.findAuthorityByPrimaryKey(authority.getId()), 2));
	}

	@RequestMapping(value = "/restNewAuthority", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewAuthority(@RequestBody String authorityJson) {
		Authority authority = new Gson().fromJson(authorityJson, Authority.class);
		appendReferences(authority);
		authorityService.saveAuthority(authority);
		return JSONObject.parse(cmiPsonService.toJsonString(authorityDAO.findAuthorityByPrimaryKey(authority.getId()), 2));
	}

	@RequestMapping(value = "/saveAuthority", method = RequestMethod.PUT)
	@ResponseBody
	public Authority saveAuthority(@RequestBody Authority authority) {
		authorityService.saveAuthority(authority);
		return authorityDAO.findAuthorityByPrimaryKey(authority.getId());
	}

	@RequestMapping(value = "/restSaveAuthority", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSaveAuthority(@RequestBody String authorityJson) {
		Authority authority = new Gson().fromJson(authorityJson, Authority.class);
		appendReferences(authority);
		CmiPsonService cmiPsonService = new CmiPsonService();
		authorityService.saveAuthority(authority);
		return JSONObject.parse(cmiPsonService.toJsonString(authorityDAO.findAuthorityByPrimaryKey(authority.getId()), 1));
	}

	@RequestMapping(value = "/restDeleteAuthority/{authorityId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeleteAuthority(@PathVariable Integer authorityId) {
		Authority authority = authorityDAO.findAuthorityByPrimaryKey(authorityId);
		authorityService.deleteAuthority(authority);
	}

	@RequestMapping(value = "/restConfirmDeleteAuthoritys")
	@ResponseBody
	public Object restConfirmDeleteAuthoritys(@RequestBody Set<Integer> deleteAuthoritysIds) {
		Set<Authority> deleteAuthoritys = authorityDAO.findAuthoritysByIds(deleteAuthoritysIds);
		Set<Authority> referencedAuthoritys = authorityService.loadReferenceAuthoritys(deleteAuthoritys);
		deleteAuthoritys.removeAll(referencedAuthoritys);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedAuthoritys);
		jsonObject.put("deleteEntitys", deleteAuthoritys);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeleteAuthoritys")
	@ResponseBody
	public Object restDeleteAuthoritys(@RequestBody Set<Authority> deleteAuthoritys) {
		Iterator<Authority> iterator = deleteAuthoritys.iterator();
		while (iterator.hasNext()) {
			Authority currentAuthority = iterator.next();
			authorityService.deleteAuthority(currentAuthority);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listAuthoritys");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadAuthority/{authorityId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadAuthority(@PathVariable Integer authorityId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(authorityDAO.findAuthorityByPrimaryKey(authorityId), 2, cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	@RequestMapping(value = "/restLoadAuthorityUsers/{authorityId}/users/{relateduserId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadAuthorityUsers(@PathVariable Integer authorityId, @PathVariable Integer relateduserId,
			@RequestBody CmiPagination cmiPagination) {
		User user = userDAO.findUserByPrimaryKey(relateduserId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(user, 2, cmiPagination));
	}

	public void appendReferences(Authority authority) {

		// 引用表是纯联系表的情况
		Set<User> usersForAuthority = new HashSet<>();
		for (User userForAuthority : authority.getUsersForAuthority()) {
			usersForAuthority.add(userService.findUserByPrimaryKey(userForAuthority.getId()));
		}
		authority.setUsersForAuthority(usersForAuthority);
	}

	@RequestMapping(value = "/restGetAuthorityUsers/{authorityId}/users", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetAuthorityUsers(@PathVariable Integer authorityId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(authorityDAO.findAuthorityByPrimaryKey(authorityId).getUsersForAuthority(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restListAuthoritys", method = RequestMethod.GET)
	@ResponseBody
	public Object restListAuthoritys() {
		return JSONObject.parse(cmiPsonService.toJsonString(authorityService.loadAuthoritys(), 2));
	}

	@RequestMapping(value = "/restListAuthoritysPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListAuthoritysPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = authorityPaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Authority> authoritys = authorityDAO.findAllAuthoritys(startResult, cmiPagination.getPaginationSize());
		String authorityString = cmiPsonService.toPsonString(authoritys, 2, cmiPagination);

		return JSONObject.parse(authorityString);
	}

	@RequestMapping("/authoritySelectBox")
	@ResponseBody
	public JSONObject authoritySelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键

			// 被引用键

			case "User":
				entitySet = userService.loadUsersByIdSet(searchValue);
				break;
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键

			// 被引用键

			case "User":
				entitySet = userDAO.findAllUsers((pageNumber - 1) * paginationSize, paginationSize);
				count = userService.countUsers();
				break;
			}
		} else {
			switch (selectItem) {
			// 外键

			// 被引用键

			case "User":
				entitySet = userDAO.findUserByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = userService.countUsersByName(queryword);
				break;
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
